<script setup lang="ts">
import { ref, onMounted,watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { setToken } from '../../utils/auth'
import { login, getUserInfo } from '../../api/user'
import { getUserMenus } from '../../api/menu'
import { processMenuData } from '@/utils/menuUtils'
import { ElMessage } from 'element-plus'

const router = useRouter()

const username = ref('')
const password = ref('')
const loading = ref(false)
const errorMessage = ref('')
const rememberMe = ref(false)
const showPassword = ref(false)
const formActive = ref(false)
const loginMode = ref('password') // 'password' 或 'qrcode'
const qrCodeUrl = ref('')
const qrCodeLoading = ref(false)

onMounted(() => {
    // 清除401错误处理标记，确保登录页正常显示
    sessionStorage.removeItem('handling_401_error')
    sessionStorage.removeItem('redirecting_to_login')
    
    // 自动填充用户名和密码
    const rememberedUsername = localStorage.getItem('rememberedUsername')
    const rememberedPassword = localStorage.getItem('rememberedPassword')
    
    if (rememberedUsername && rememberedUsername !== 'null') {
      username.value = rememberedUsername
      rememberMe.value = true
    }
    
    // 修复：如果有记住的密码，直接填充，不需要依赖rememberMe状态
    if (rememberedPassword && rememberedPassword !== 'null') {
      password.value = rememberedPassword
      // 确保记住我选项被勾选
      rememberMe.value = true
    }
    
    setTimeout(() => {
      formActive.value = true
    }, 100)
})

const handleLogin = async () => {
  if (!username.value || !password.value) {
    errorMessage.value = '请输入用户名和密码'
    return
  }
  loading.value = true
  errorMessage.value = ''
  try {
    // 登录
    const loginResult = await login({
      username: username.value,
      password: password.value
    })
    console.debug('登录结果:', loginResult)
    setToken(loginResult.access_token)

    // 获取用户信息
    const userinfo = await getUserInfo()
    console.debug('用户信息:', userinfo)

    // 取第一个角色作为默认角色
    const userRole = userinfo.roles[0]
    localStorage.setItem('user_roles', JSON.stringify(userinfo.roles))
    localStorage.setItem('userRole', userRole)
    
    // 获取用户菜单权限
    const processedMenus = processMenuData(await getUserMenus())
    localStorage.setItem('userMenus', JSON.stringify(processedMenus))

    // 始终保存当前登录的用户名（用于侧边栏显示）
    localStorage.setItem('currentUsername', userinfo.nickname)

    // 记住用户名和密码逻辑（用于下次登录时自动填充）
    if (rememberMe.value) {
      localStorage.setItem('rememberedUsername', username.value)
      localStorage.setItem('rememberedPassword', password.value)
    } else {
      localStorage.removeItem('rememberedUsername')
      localStorage.removeItem('rememberedPassword')
    }
    
    // 显示登录成功消息
    ElMessage({
      message: '登录成功',
      type: 'success'
    })
    if(username.value==='admin' || username.value === 'staff'){
      router.push('/')
    }
    else{
      router.push('/chat')
    }
  } catch (error: any) {
    errorMessage.value = error.message || '登录失败，请检查用户名和密码'
  } finally {
    console.error('登录失败')
    loading.value = false
  }
}
// 监听 rememberMe 变化，取消勾选时清除用户名和密码
watch(rememberMe, (val) => {
  if (!val) {
    localStorage.removeItem('rememberedUsername')
    localStorage.removeItem('rememberedPassword')
  }
})
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

// 切换登录模式
const switchLoginMode = (mode: 'password' | 'qrcode') => {
  loginMode.value = mode
  errorMessage.value = ''
  if (mode === 'qrcode') {
    generateQRCode()
  }
}

// 生成二维码
const generateQRCode = async () => {
  qrCodeLoading.value = true
  try {
    // 模拟生成二维码的API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 这里应该调用后端API获取二维码
    // const response = await api.generateQRCode()
    // qrCodeUrl.value = response.data.qrCodeUrl

    // 模拟二维码URL
    qrCodeUrl.value = `data:image/svg+xml;base64,${btoa(`
      <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
        <rect width="200" height="200" fill="white"/>
        <rect x="20" y="20" width="160" height="160" fill="none" stroke="black" stroke-width="2"/>
        <text x="100" y="100" text-anchor="middle" font-family="Arial" font-size="12" fill="black">
          扫码登录
        </text>
        <text x="100" y="120" text-anchor="middle" font-family="Arial" font-size="10" fill="gray">
          请使用手机扫码
        </text>
      </svg>
    `)}`

    // 开始轮询检查扫码状态
    checkQRCodeStatus()
  } catch (error) {
    console.error('生成二维码失败:', error)
    errorMessage.value = '生成二维码失败，请重试'
  } finally {
    qrCodeLoading.value = false
  }
}

// 检查二维码扫码状态
const checkQRCodeStatus = () => {
  // 这里应该轮询后端API检查扫码状态
  // 模拟扫码成功的逻辑
  console.log('开始检查二维码状态...')
}
</script>
<template>
  <div class="login-page">
    <div class="login-container" :class="{ 'active': formActive }">
      <!-- 左侧品牌区域 -->
      <div class="login-left">
        <div class="brand-content">
          <div class="logo-section">
            <div class="logo-circle">
              <img src="../../assets/十一建logo/logo.png" alt="Logo" />
            </div>
          </div>
          
          <h1 class="system-title">十一智库系统</h1>
          <p class="system-desc">智能化企业管理平台</p>
          
          <!-- 特色卡片 -->
          <div class="feature-cards">
            <div class="feature-card">
              <span class="feature-icon">📊</span>
              <span>高效便捷</span>
            </div>
            <div class="feature-card">
              <span class="feature-icon">🔒</span>
              <span>安全可靠</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 右侧登录表单 -->
      <div class="login-right">
        <div class="form-container">
          <div class="login-header">
            <h2>欢迎回来</h2>
            <p>请登录您的账户以继续</p>
          </div>

          <!-- 登录方式切换 -->
          <div class="login-mode-tabs">
            <button
              type="button"
              class="mode-tab"
              :class="{ active: loginMode === 'password' }"
              @click="switchLoginMode('password')"
            >
              <span class="tab-icon">🔑</span>
              密码登录
            </button>
            <button
              type="button"
              class="mode-tab"
              :class="{ active: loginMode === 'qrcode' }"
              @click="switchLoginMode('qrcode')"
            >
              <span class="tab-icon">📱</span>
              扫码登录
            </button>
          </div>

          <div class="login-form">
            <transition name="fade">
              <div v-if="errorMessage" class="error-message">
                {{ errorMessage }}
              </div>
            </transition>

            <!-- 密码登录表单 -->
            <div v-if="loginMode === 'password'" class="password-login">
              <div class="form-group">
                <label>用户名</label>
                <div class="input-container">
                  <span class="input-icon">👤</span>
                  <input
                    type="text"
                    v-model="username"
                    placeholder="请输入用户名"
                    :disabled="loading"
                  />
                </div>
              </div>

              <div class="form-group">
                <label>密码</label>
                <div class="input-container">
                  <span class="input-icon">🔒</span>
                  <input
                    :type="showPassword ? 'text' : 'password'"
                    v-model="password"
                    placeholder="请输入密码"
                    :disabled="loading"
                    @keyup.enter="handleLogin"
                  />
                  <button
                    type="button"
                    class="toggle-password"
                    @click="togglePasswordVisibility"
                  >
                    👁️
                  </button>
                </div>
              </div>

              <div class="form-options">
                <label class="checkbox-label">
                  <input type="checkbox" v-model="rememberMe" />
                  <span class="checkmark"></span>
                  <span>记住我</span>
                </label>
                <a href="#" class="forgot-link">忘记密码?</a>
              </div>

              <button
                class="login-button"
                @click="handleLogin"
                :disabled="loading"
              >
                <span v-if="!loading">登录 →</span>
                <span v-else>登录中...</span>
              </button>
            </div>

            <!-- 扫码登录 -->
            <div v-else class="qrcode-login">
              <div class="qrcode-container">
                <div v-if="qrCodeLoading" class="qrcode-losading">
                  <div class="loading-spinner">⏳</div>
                  <p>正在生成二维码...</p>
                </div>
                <div v-else-if="qrCodeUrl" class="qrcode-display">
                  <img :src="qrCodeUrl" alt="登录二维码" class="qrcode-image" />
                  <p class="qrcode-tip">请使用手机扫描二维码登录</p>
                  <button
                    type="button"
                    class="refresh-qrcode"
                    @click="generateQRCode"
                  >
                    🔄 刷新二维码
                  </button>
                </div>
                <div v-else class="qrcode-error">
                  <p>二维码生成失败</p>
                  <button
                    type="button"
                    class="retry-qrcode"
                    @click="generateQRCode"
                  >
                    重新生成
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div class="login-footer">
            <p>© 2025 陕西建工控股集团有限公司 版权所有</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped>
.login-page {
  min-height: 100vh;
  background: var(--minimal-bg);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  display: flex;
  width: 900px;
  max-width: 95%;
  height: 700px;
  background: var(--minimal-card-bg);
  border-radius: var(--minimal-radius);
  box-shadow: var(--minimal-shadow);
  overflow: hidden;
  opacity: 0;
  transform: translateY(20px);
  transition: all 0.6s ease;
  border: 1px solid var(--minimal-border);
}

.login-container.active {
  opacity: 1;
  transform: translateY(0);
}

.login-left {
  width: 45%;
  background: var(--minimal-primary-gradient);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px 40px;
  color: white;
  position: relative;
}

.brand-content {
  text-align: center;
  width: 100%;
}

.logo-section {
  margin-bottom: 40px;
}

.logo-circle {
  width: 120px;
  height: 120px;
  background: var(--minimal-glass-bg);
  backdrop-filter: blur(var(--minimal-glass-blur));
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  border: 2px solid rgba(255, 255, 255, 0.2);
  transition: transform 0.3s ease;
}

.logo-circle:hover {
  transform: scale(1.05);
}

.logo-circle img {
  width: 80px;
  height: 80px;
  object-fit: contain;
}

.system-title {
  font-size: 2.2em;
  font-weight: 700;
  color: white;
  margin-bottom: 16px;
  font-family: var(--minimal-font-family);
  letter-spacing: 0.5px;
}

.system-desc {
  font-size: 1.1em;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 40px;
  font-weight: 400;
}

.feature-cards {
  display: flex;
  gap: 16px;
  justify-content: center;
}

.feature-card {
  background: var(--minimal-glass-bg);
  backdrop-filter: blur(var(--minimal-glass-blur));
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 12px 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 0.9em;
  font-weight: 500;
  transition: transform 0.3s ease;
}

.feature-card:hover {
  transform: translateY(-2px);
}

.feature-icon {
  font-size: 1.2em;
}

.login-right {
  width: 55%;
  padding: 60px 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--minimal-card-bg);
}

.form-container {
  width: 100%;
  max-width: 380px;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h2 {
  font-size: 2em;
  font-weight: 600;
  color: var(--minimal-text);
  margin-bottom: 8px;
  font-family: var(--minimal-font-family);
}

.login-header p {
  color: rgba(34, 34, 34, 0.6);
  font-size: 1em;
}

.form-group {
  margin-bottom: 24px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: var(--minimal-text);
  font-size: 0.9em;
  font-weight: 500;
}

.input-container {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 16px;
  z-index: 2;
  font-size: 1.1em;
  color: var(--minimal-primary-gradient);
}

.input-container input {
  width: 100%;
  padding: 16px 16px 16px 48px;
  border: 2px solid var(--minimal-border);
  border-radius: 12px;
  font-size: 1em;
  background: var(--minimal-bg);
  transition: all 0.3s ease;
  color: var(--minimal-text);
  font-family: var(--minimal-font-family);
}

.input-container input:focus {
  outline: none;
  border-color: var(--minimal-primary-gradient);
  background: var(--minimal-card-bg);
  box-shadow: 0 0 0 3px rgba(91, 124, 255, 0.1);
}

.input-container input::placeholder {
  color: rgba(34, 34, 34, 0.4);
}

.toggle-password {
  position: absolute;
  right: 16px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 1.1em;
  color: rgba(34, 34, 34, 0.5);
  transition: color 0.3s ease;
}

.toggle-password:hover {
  color: var(--minimal-primary-gradient);
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 0.9em;
  color: var(--minimal-text);
  gap: 8px;
}

.checkbox-label input {
  display: none;
}

.checkmark {
  width: 18px;
  height: 18px;
  border: 2px solid var(--minimal-border);
  border-radius: 4px;
  position: relative;
  transition: all 0.3s ease;
}

.checkbox-label input:checked + .checkmark {
  background: var(--minimal-primary-gradient);
  border-color: var(--minimal-primary-gradient);
}

.checkbox-label input:checked + .checkmark::after {
  content: '✓';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.forgot-link {
  color: var(--minimal-primary-gradient);
  text-decoration: none;
  font-size: 0.9em;
  transition: opacity 0.3s ease;
}

.forgot-link:hover {
  opacity: 0.8;
}

.login-button {
  width: 100%;
  padding: 16px;
  background: var(--minimal-primary-gradient);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1.1em;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 24px;
  font-family: var(--minimal-font-family);
}

.login-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(91, 124, 255, 0.3);
}

.login-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.login-footer {
  text-align: center;
}

.login-footer p {
  color: rgba(34, 34, 34, 0.5);
  font-size: 0.8em;
}

.error-message {
  background: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  font-size: 0.9em;
  border-left: 3px solid #f56c6c;
}

.fade-enter-active, .fade-leave-active {
  transition: all 0.3s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
    width: 100%;
    max-width: 400px;
    height: auto;
  }
  
  .login-left, .login-right {
    width: 100%;
  }
  
  .login-left {
    padding: 40px 30px;
    min-height: 280px;
  }
  
  .login-right {
    padding: 40px 30px;
  }
  
  .feature-cards {
    display: none;
  }
  
  .system-title {
    font-size: 1.8em;
  }
  
  .login-header h2 {
    font-size: 1.6em;
  }
}

/* 登录方式切换标签 */
.login-mode-tabs {
  display: flex;
  background: #f8fafc;
  border-radius: 8px;
  padding: 4px;
  margin-bottom: 24px;
  gap: 4px;
}

.mode-tab {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 16px;
  border: none;
  border-radius: 6px;
  background: transparent;
  color: #6b7280;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.mode-tab.active {
  background: white;
  color: #4f46e5;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.mode-tab:hover:not(.active) {
  color: #374151;
  background: rgba(255, 255, 255, 0.5);
}

.tab-icon {
  font-size: 16px;
}

/* 扫码登录样式 */
.qrcode-login {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.qrcode-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 40px;
}

.qrcode-loading .loading-spinner {
  font-size: 24px;
  animation: spin 1s linear infinite;
}

.qrcode-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.qrcode-image {
  width: 200px;
  height: 200px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: white;
}

.qrcode-tip {
  color: #6b7280;
  font-size: 14px;
  text-align: center;
  margin: 0;
}

.refresh-qrcode,
.retry-qrcode {
  padding: 8px 16px;
  background: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.refresh-qrcode:hover,
.retry-qrcode:hover {
  background: #e5e7eb;
  border-color: #9ca3af;
}

.qrcode-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 40px;
  color: #ef4444;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
